package com.shouer.doc.ui.ordermanager;

import android.graphics.Matrix;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;

import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.shouer.doc.R;
import com.shouer.doc.application.App;
import com.shouer.doc.common.util.ScreenUtils;
import com.shouer.doc.dialog.ShouerLoadingDialogUtil;
import com.shouer.doc.event.UnReadCountEvent;
import com.shouer.doc.ui.LasyFragment;
import com.shouer.doc.ui.login.model.UserModel;
import com.shouer.doc.ui.neworder.model.HealthRecord;
import com.shouer.doc.ui.neworder.model.SimpleOrderModel;
import com.shouer.doc.ui.ordermanager.adapter.FinishedOrderAdapter;
import com.shouer.doc.ui.ordermanager.adapter.HealthRecordAdapter;
import com.shouer.doc.ui.ordermanager.adapter.InOrderAdapter;
import com.shouer.doc.ui.ordermanager.presenter.HealthRecordPresenterCompl;
import com.shouer.doc.ui.ordermanager.presenter.IHealthRecordPresenter;
import com.shouer.doc.ui.ordermanager.presenter.IOrderManagerPresenter;
import com.shouer.doc.ui.ordermanager.presenter.OrderManagerPresenterCompl;
import com.shouer.doc.ui.ordermanager.view.IOrderManagerView;
import com.shouer.doc.widget.OrderItemDecoration;
import com.shouer.doc.widget.ShouerLayoutManager;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imkit.manager.IUnReadMessageObserver;
import io.rong.imlib.model.Conversation;

/**
 * Created by ZXL on 2016/11/25.
 */

public class OrderManagerFragment extends LasyFragment implements IOrderManagerView ,IUnReadMessageObserver{

    private App app;
    private IOrderManagerPresenter managerPresenter;
    private IHealthRecordPresenter healthRecordPresenter;
    private View mRootView;
    private boolean isPrepared;

    @BindView(R.id.title)
    protected View titleView;
    @BindView(R.id.tab_layout)
    protected View tabLayout;
    @BindView(R.id.tab1)
    protected View tab1;
    @BindView(R.id.tab2)
    protected View tab2;
    @BindView(R.id.navigation_view)
    protected ImageView navigationView;

    @BindView(R.id.order_layout)
    protected View orderLayout;
    @BindView(R.id.inorder_list)
    protected XRecyclerView inorderList;
    @BindView(R.id.finished_list)
    protected XRecyclerView finishedList;
    @BindView(R.id.order_tab1)
    protected View orderTab1;
    @BindView(R.id.order_tab2)
    protected View orderTab2;

    @BindView(R.id.healthrecord_layout)
    protected View healthrecordLayout;
    @BindView(R.id.healthrecord_list)
    protected XRecyclerView healthrecordList;
    @BindView(R.id.finished_healthrecord_list)
    protected XRecyclerView finishedHealthrecordList;
    @BindView(R.id.healthrecord_tab1)
    protected View healthrecordTab1;
    @BindView(R.id.healthrecord_tab2)
    protected View healthrecordTab2;

    private InOrderAdapter orderInOrderListAdapter;
    private FinishedOrderAdapter finishedOrderListAdapter;
    private Animation animation;
    private int offset,one;

    private HealthRecordAdapter healthRecordAdapter;
    private HealthRecordAdapter fiishedHealthRecordAdapter;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        app = (App) getActivity().getApplicationContext();
        managerPresenter = new OrderManagerPresenterCompl(this);
        healthRecordPresenter=new HealthRecordPresenterCompl(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        if (null == mRootView) {
            mRootView = inflater.inflate(R.layout.fragment_ordermanager_layout, container, false);
            ButterKnife.bind(this, mRootView);
            initViews();
            isPrepared = true;
            lazyLoad();
        }
        return mRootView;
    }

    private void initViews()
    {

        ShouerLayoutManager layoutManager1 = new ShouerLayoutManager(getContext());
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        inorderList.setLayoutManager(layoutManager1);
        inorderList.addItemDecoration(new OrderItemDecoration(ScreenUtils.dip2px(getContext(), 15)));

        orderInOrderListAdapter = new InOrderAdapter(getContext(), this);
        inorderList.setRefreshProgressStyle(ProgressStyle.SquareSpin);
        inorderList.setLoadingMoreProgressStyle(ProgressStyle.SquareSpin);
        inorderList.setAdapter(orderInOrderListAdapter);
        inorderList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                //refresh data here
                Log.d(XRecyclerView.class.getSimpleName(), "onRefresh()");
                if (!managerPresenter.refreshOrderInOrder()) {
                    inorderList.refreshComplete();
                }
            }

            @Override
            public void onLoadMore() {
                // load more data here
                Log.d(XRecyclerView.class.getSimpleName(), "onLoadMore()");
                if (!managerPresenter.loadMoreOrderInOrder()) {
                    inorderList.loadMoreComplete();
                }
            }
        });


        ShouerLayoutManager layoutManager2 = new ShouerLayoutManager(getContext());
        layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
        finishedList.setLayoutManager(layoutManager2);
        finishedList.addItemDecoration(new OrderItemDecoration(ScreenUtils.dip2px(getContext(), 15)));

        finishedOrderListAdapter = new FinishedOrderAdapter(getContext(), managerPresenter);
        finishedList.setRefreshProgressStyle(ProgressStyle.SquareSpin);
        finishedList.setLoadingMoreProgressStyle(ProgressStyle.SquareSpin);
        finishedList.setAdapter(finishedOrderListAdapter);
        finishedList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                //refresh data here
                Log.d(XRecyclerView.class.getSimpleName(), "onRefresh()");
                if (!managerPresenter.refreshFinishedOrder()) {
                    finishedList.refreshComplete();
                }
            }

            @Override
            public void onLoadMore() {
                // load more data here
                Log.d(XRecyclerView.class.getSimpleName(), "onLoadMore()");
                if (!managerPresenter.loadMoreFinishedOrder()) {
                    finishedList.loadMoreComplete();
                }
            }
        });

        ShouerLayoutManager layoutManager3 = new ShouerLayoutManager(getContext());
        layoutManager3.setOrientation(LinearLayoutManager.VERTICAL);
        healthrecordList.setLayoutManager(layoutManager3);
        healthrecordList.addItemDecoration(new OrderItemDecoration(ScreenUtils.dip2px(getContext(), 15)));

        healthRecordAdapter = new HealthRecordAdapter(getContext(), managerPresenter);
        healthrecordList.setRefreshProgressStyle(ProgressStyle.SquareSpin);
        healthrecordList.setLoadingMoreProgressStyle(ProgressStyle.SquareSpin);
        healthrecordList.setAdapter(healthRecordAdapter);
        healthrecordList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                //refresh data here
                Log.d(XRecyclerView.class.getSimpleName(), "onRefresh()");
                if (!healthRecordPresenter.refreshHealthRecord()) {
                    healthrecordList.refreshComplete();
                }
            }

            @Override
            public void onLoadMore() {
                // load more data here
                Log.d(XRecyclerView.class.getSimpleName(), "onLoadMore()");
                if (!healthRecordPresenter.loadMoreHealthRecord()) {
                    healthrecordList.loadMoreComplete();
                }
            }
        });

        ShouerLayoutManager layoutManager4 = new ShouerLayoutManager(getContext());
        layoutManager4.setOrientation(LinearLayoutManager.VERTICAL);
        finishedHealthrecordList.setLayoutManager(layoutManager4);
        finishedHealthrecordList.addItemDecoration(new OrderItemDecoration(ScreenUtils.dip2px(getContext(), 15)));

        fiishedHealthRecordAdapter = new HealthRecordAdapter(getContext(), managerPresenter);
        finishedHealthrecordList.setRefreshProgressStyle(ProgressStyle.SquareSpin);
        finishedHealthrecordList.setLoadingMoreProgressStyle(ProgressStyle.SquareSpin);
        finishedHealthrecordList.setAdapter(fiishedHealthRecordAdapter);
        finishedHealthrecordList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                //refresh data here
                Log.d(XRecyclerView.class.getSimpleName(), "onRefresh()");
                if (!healthRecordPresenter.refreshFinishedHealthRecord()) {
                    finishedList.refreshComplete();
                }
            }

            @Override
            public void onLoadMore() {
                // load more data here
                Log.d(XRecyclerView.class.getSimpleName(), "onLoadMore()");
                if (!healthRecordPresenter.loadMoreFinishedHealthRecord()) {
                    finishedList.loadMoreComplete();
                }
            }
        });


        tab1.setSelected(true);
        orderTab1.setSelected(true);
        healthrecordTab1.setSelected(true);


        int imgWidth = (int) getResources().getDimension(R.dimen.navigation_img_width);
        offset = ((ScreenUtils.getScreenWidth(getContext())-ScreenUtils.dip2px(getContext(),180))/2 - imgWidth) / 2;
        one = (ScreenUtils.getScreenWidth(getContext())-ScreenUtils.dip2px(getContext(),180))/2;
        Matrix matrix = new Matrix();
        matrix.postTranslate(offset, 0);
        navigationView.setImageMatrix(matrix);// 设置动画初始位置

        if (app.getUserDocInfo().getRecordAccessRight() == 0) {
            tabLayout.setVisibility(View.GONE);
            navigationView.setVisibility(View.GONE);
            titleView.setVisibility(View.VISIBLE);
        } else {
            titleView.setVisibility(View.GONE);
            tabLayout.setVisibility(View.VISIBLE);
            navigationView.setVisibility(View.VISIBLE);
        }

        RongIM.getInstance().addUnReadMessageCountChangedObserver(OrderManagerFragment.this, Conversation.ConversationType.GROUP);

    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        RongIM.getInstance().removeUnReadMessageCountChangedObserver(this);
        managerPresenter.onDestroy();
        healthRecordPresenter.onDestroy();
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        if (inorderList.getVisibility()==View.VISIBLE)
        {
            if (orderInOrderListAdapter.getItemCount()==0)
            {
                managerPresenter.refreshOrderInOrder();
            }
        }else
        {
            if (finishedOrderListAdapter.getItemCount()==0)
            {
                ShouerLoadingDialogUtil.getInstance().show(getContext());
                managerPresenter.refreshFinishedOrder();
            }
        }
    }

    @OnClick(value = {R.id.tab1,R.id.tab2,R.id.order_tab1,R.id.order_tab2,R.id.healthrecord_tab1,R.id.healthrecord_tab2})
    protected void onClick(View view) {

        switch (view.getId())
        {
            case R.id.tab1:
                if (orderLayout.getVisibility()!=View.VISIBLE)
                {
                    tab1.setSelected(true);
                    tab2.setSelected(false);
                    setSelectedForDirectiveImg(0);
                    healthrecordLayout.setVisibility(View.GONE);
                    orderLayout.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.tab2:
                if (healthrecordLayout.getVisibility()!=View.VISIBLE)
                {
                    tab2.setSelected(true);
                    tab1.setSelected(false);
                    setSelectedForDirectiveImg(1);
                    orderLayout.setVisibility(View.GONE);
                    healthrecordLayout.setVisibility(View.VISIBLE);

                    if (healthrecordList.getVisibility()==View.VISIBLE&&healthRecordAdapter.getItemCount()==0)
                    {
                        ShouerLoadingDialogUtil.getInstance().show(getContext());
                        healthRecordPresenter.refreshHealthRecord();
                    }

                    if (finishedHealthrecordList.getVisibility()==View.VISIBLE&&finishedOrderListAdapter.getItemCount()==0)
                    {
                        ShouerLoadingDialogUtil.getInstance().show(getContext());
                        healthRecordPresenter.refreshFinishedHealthRecord();
                    }

                }
                break;
            case R.id.order_tab1:
                if (inorderList.getVisibility()!=View.VISIBLE)
                {
                    if (orderInOrderListAdapter.getItemCount()==0)
                    {
                        ShouerLoadingDialogUtil.getInstance().show(getContext());
                        managerPresenter.refreshOrderInOrder();
                    }
                    orderTab1.setSelected(true);
                    orderTab2.setSelected(false);
                    finishedList.setVisibility(View.GONE);
                    inorderList.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.order_tab2:
                if (finishedList.getVisibility()!=View.VISIBLE)
                {
                    if (finishedOrderListAdapter.getItemCount()==0)
                    {
                        ShouerLoadingDialogUtil.getInstance().show(getContext());
                        managerPresenter.refreshFinishedOrder();
                    }
                    orderTab1.setSelected(false);
                    orderTab2.setSelected(true);
                    inorderList.setVisibility(View.GONE);
                    finishedList.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.healthrecord_tab1:
                if (healthrecordList.getVisibility()!=View.VISIBLE)
                {
                    if (healthRecordAdapter.getItemCount()==0)
                    {
                        ShouerLoadingDialogUtil.getInstance().show(getContext());
                        healthRecordPresenter.refreshHealthRecord();
                    }
                    healthrecordTab1.setSelected(true);
                    healthrecordTab2.setSelected(false);
                    finishedHealthrecordList.setVisibility(View.GONE);
                    healthrecordList.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.healthrecord_tab2:
                if (finishedHealthrecordList.getVisibility()!=View.VISIBLE)
                {
                    if (finishedOrderListAdapter.getItemCount()==0)
                    {
                        ShouerLoadingDialogUtil.getInstance().show(getContext());
                        healthRecordPresenter.refreshFinishedHealthRecord();
                    }
                    healthrecordTab2.setSelected(true);
                    healthrecordTab1.setSelected(false);
                    healthrecordList.setVisibility(View.GONE);
                    finishedHealthrecordList.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    private void setSelectedForDirectiveImg(int position) {

        if (position == 0) {
            animation = new TranslateAnimation(one, 0, 0, 0);
        } else {
            animation = new TranslateAnimation(0, one, 0, 0);
        }
        animation.setFillAfter(true);// True:图片停在动画结束位置
        animation.setDuration(300);
        navigationView.startAnimation(animation);

    }

    @Override
    public App getApp() {
        return app;
    }

    @Override
    public UserModel getUser() {
        return app.getUserModel();
    }

    @Override
    public InOrderAdapter getOrdInOrderAdapter() {
        return orderInOrderListAdapter;
    }

    @Override
    public FinishedOrderAdapter getFinishedAdapter() {
        return finishedOrderListAdapter;
    }

    @Override
    public void loadOrdInOrdFailed() {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        inorderList.refreshComplete();
        inorderList.loadMoreComplete();
    }

    @Override
    public void loadFinishedOrderFailed() {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        finishedList.refreshComplete();
        finishedList.loadMoreComplete();
    }

    @Override
    public void loadHealthRecordFailed() {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        healthrecordList.refreshComplete();
        healthrecordList.loadMoreComplete();
    }

    @Override
    public void loadFinishedHealthRecordFailed() {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        finishedHealthrecordList.refreshComplete();
        finishedHealthrecordList.loadMoreComplete();
    }

    @Override
    public void refreshOrdInOrdList(List<SimpleOrderModel> orderModels) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        inorderList.refreshComplete();
        inorderList.loadMoreComplete();
        orderInOrderListAdapter.refreshDocList(orderModels);

    }

    @Override
    public void attachOrdIOrdList(List<SimpleOrderModel> orderModels) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        inorderList.refreshComplete();
        inorderList.loadMoreComplete();
        orderInOrderListAdapter.attachToDocList(orderModels);
    }

    @Override
    public void refreshFinishedOrdList(List<SimpleOrderModel> orderModels) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        finishedList.refreshComplete();
        finishedList.loadMoreComplete();
        finishedOrderListAdapter.refreshDocList(orderModels);
    }

    @Override
    public void attachFinishedOrdList(List<SimpleOrderModel> orderModels) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        finishedList.refreshComplete();
        finishedList.loadMoreComplete();
        finishedOrderListAdapter.attachToDocList(orderModels);
    }

    @Override
    public void refreshHealthRecordList(List<HealthRecord> healthRecords) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        healthrecordList.refreshComplete();
        healthrecordList.loadMoreComplete();
        healthRecordAdapter.refreshHealthRecordList(healthRecords);
    }

    @Override
    public void attachHealthRecordList(List<HealthRecord> healthRecords) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        healthrecordList.refreshComplete();
        healthrecordList.loadMoreComplete();
        healthRecordAdapter.attachToHealthRecordList(healthRecords);
    }

    @Override
    public void refreshFinishedHealthRecordList(List<HealthRecord> healthRecords) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        finishedHealthrecordList.refreshComplete();
        finishedHealthrecordList.loadMoreComplete();
        fiishedHealthRecordAdapter.refreshHealthRecordList(healthRecords);
    }

    @Override
    public void attachFinishedHealthRecordList(List<HealthRecord> healthRecords) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        finishedHealthrecordList.refreshComplete();
        finishedHealthrecordList.loadMoreComplete();
        fiishedHealthRecordAdapter.attachToHealthRecordList(healthRecords);
    }

    @Override
    public void refreshUnReadCount(SimpleOrderModel orderModel) {
        managerPresenter.refreshUnReadCount(orderModel);
    }

    /**
     * 查询订单未读消息
     * */
    @Override
    public void onOrderInOrderItemClick(SimpleOrderModel orderModel) {
        managerPresenter.onOrderInOrderItemClick(orderModel);
    }

    /**
     * 查询订单未读消息成功后刷新Adapter
     * */
    @Override
    public void refreshOrdItem(SimpleOrderModel orderModel) {

        if (null!=orderInOrderListAdapter)
        {
            orderInOrderListAdapter.refreshOrdItem(orderModel);
        }
    }

    @Override
    public void refreshUnReadCount(String orderId, int count) {
        if (null!=orderInOrderListAdapter)
        {
            orderInOrderListAdapter.refreshOrdCount(orderId,count);
        }
    }

    @Override
    public void onCountChanged(int i) {
        Log.i(OrderManagerFragment.class.getSimpleName(),"onCountChanged:"+i);
        if (i>0)
        {
            orderInOrderListAdapter.setReQueryCount();
            if (null!=orderInOrderListAdapter)
            {
                orderInOrderListAdapter.notifyDataSetChanged();
            }
            EventBus.getDefault().post(new UnReadCountEvent(i));
        }
    }
}
